package com.firefightingiot_data.data.support.udp;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * @Author: YangYu
 * @ClassName: UdpClientUtils
 * @Date: Created in 9:23 2021/9/24
 * @Description: UDP客户端服务
 */
@Slf4j
public class UdpClientUtils {


    public static void send(String msg) throws IOException {
        byte[] buf = msg.getBytes();
        try {
            //服务器地址
            InetAddress address = InetAddress.getByName("192.168.119.1");
            //服务器的端口号
            int port = 8607;
            //创建发送方的数据报信息
            DatagramPacket dataGramPacket = new DatagramPacket(buf, buf.length, address, port);
            //创建套接字
            DatagramSocket socket = new DatagramSocket();
            //通过套接字发送数据
            socket.send(dataGramPacket);

            //接收服务器反馈数据
            byte[] backbuf = new byte[1024];
            DatagramPacket backPacket = new DatagramPacket(backbuf, backbuf.length);
            //接收返回数据
            socket.receive(backPacket);
            String backMsg = new String(backbuf, 0, backPacket.getLength());
            System.out.println("服务器返回的数据为:" + backMsg);
            socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) throws Exception {
//       send("yangyu");
//    }
public static void main(String[] args) throws IOException {
    DatagramSocket socket = new DatagramSocket();
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        //readLine读取输入，转换为byte放入包中发送出去
        String data = reader.readLine();
        byte[] datas = data.getBytes();
        DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("192.168.119.1", 8607));
        socket.send(packet);
        //接收服务器反馈数据
        byte[] backbuf = new byte[1024];
        DatagramPacket backPacket = new DatagramPacket(backbuf, backbuf.length);
        //接收返回数据
        socket.receive(backPacket);
        String backMsg = new String(backbuf, 0, backPacket.getLength());
        System.out.println("服务器返回的数据为:" + backMsg);
        if (data.equals("bye")){
            break;
        }
    }
    socket.close();
}
}
